package logging

import (
	"context"

	"github.com/sirupsen/logrus"
)

type contextKey struct {
	key string
}

var (
	loggerCtxKey = &contextKey{"logger"}
	loggerEntry  = logrus.NewEntry(logrus.New())
)

// GetLogger returns the global logger
func GetLogger() *logrus.Entry {
	return loggerEntry
}

// ForLoggerContext return logger
func ForLoggerContext(ctx context.Context) *logrus.Entry {
	raw := ctx.Value(loggerCtxKey)
	if raw == nil {
		return loggerEntry
	}
	return raw.(*logrus.Entry)
}

// WithLoggerContext wrap logger in context
func WithLoggerContext(ctx context.Context, logger *logrus.Entry) context.Context {
	ctxn := context.WithValue(ctx, loggerCtxKey, logger)
	return ctxn
}

// WithField add field to logger
func WithField(ctx context.Context, key string, val interface{}) context.Context {
	logger := ForLoggerContext(ctx).WithField(key, val)
	return WithLoggerContext(ctx, logger)
}

// WithFields add fields to logger
func WithFields(ctx context.Context, fields logrus.Fields) context.Context {
	logger := ForLoggerContext(ctx).WithFields(fields)
	return WithLoggerContext(ctx, logger)
}
